<template>
<view class="container" :style="'height:' + (ProductshowWay==1? '100%':'')"> 
<!-- 头部 -->
 <view class="typeSearchContainer"> 
    <view class="search_input_bg">
      <view class="search_input">
        <view class="search_input_left">
          <image class="input_img" src="https://image1.sansancloud.com/xianhua/2018_9/14/16/25/0_222.jpg?x-oss-process=style/preview_120"></image>
          <input class="input" @confirm="getSearchProductName" @input="searchProductValue" placeholder="搜索产品名"></input>
        </view>
        <view class="empty_button" @tap="getSearchProductName"><text>x</text></view>
      </view>
    </view>
    <view class="typeSearch">
     <view class="flexCenter" data-index="0" style="width:85%">
       <scroll-view scroll-x class="tab-h" :scroll-into-view="'tab_'+positionTab" scroll-with-animation="true">
         <view v-for="(type, index) in productType" :key="index" :data-type="type" @tap="bindTypeItem" :id="'tab_'+type.id" class="tab-item" :style="'color:' + type.colorAtive + ';border-bottom:' + (type.active?'2rpx solid '+type.colorAtive:'')">{{type.name}}</view>
       </scroll-view>
     </view>
    
     <view class="flexCenter" @tap="bindProductshowWay" style="width:100rpx">
        <view class="border_left"></view>
        <block v-if="ProductshowWay ==1">
          <image src="https://image1.sansancloud.com/xianhua/2018_9/13/12/1/42_584.jpg"></image>
        </block>
        <block v-if="ProductshowWay == 2">
          <image src="https://image1.sansancloud.com/xianhua/2018_9/14/14/10/32_257.jpg"></image>
        </block>
     </view>
    </view>
  </view>


    <block v-if="ProductshowWay == 2">
     <view class="product_page_container2" :style="'height:' + (ProductshowWay==1? '100%':'')">
        <block v-if="!! productData">
          <view class="product_items2" :data-info="result" @tap="toProductDetail" v-for="(result, index) in productData" :key="index">
            <image mode="aspectFill" :src="result.imagePath + '?x-oss-process=style/preview'"></image>
            <view class="product_items2_view1">
              <text class="product_name">{{result.name}}</text>
              <text class="location_name" v-if="result.longitude>0">{{result.location}}</text>
              <text class="location_name" v-else>{{result.description}}</text>
              <scroll-view class="tags_content" scroll-x>
                <text class="tags_item" v-if="result.tagArray" v-for="(tags, index2) in result.tagArray" :key="index2">{{tags}}</text>
              </scroll-view>
              <view class="product_price">
                ￥{{result.price}}
                <text v-if="result.unitShow" style="color:#bbb;font-size:24rpx;margin-left:4rpx;letter-spacing:4rpx;">/{{result.unitShow}}</text>
              </view>
            </view>
            
          </view>
        </block>

        <block v-else>
          <view class="noproduct">
            <image mode="widthFix" src="https://image1.sansancloud.com/xianhua/2019_12/16/15/54/55_950.jpg?x-oss-process=style/preview_120"></image>
            <text>没有相关商品</text>
          </view>
        </block>
      </view>
    </block>


    <block v-if="ProductshowWay == 1">
     <scroll-view class="product_page_container2" :style="'height:' + (ProductshowWay==1? '100%':'')">
          <map class="mapItem" id="map" :longitude="localPoint.longitude" :latitude="localPoint.latitude" scale="14" @controltap="controltap" :markers="markers" @markertap="markertap" @regionchange="regionchange" show-location="true" style="width: 100%; height: 100%;" @tap="hiddenProInfo">
            <cover-view class="play">
               <cover-image class="img" src="https://image1.sansancloud.com/xianhua/2020_1/19/19/33/5_703.jpg?x-oss-process=style/preview_120" style="width:80rpx;height:80rpx;"></cover-image>
            </cover-view>
          </map>
          <cover-view class="bottom_tap">
            <cover-view class="return_index">
              <cover-image src="https://image1.sansancloud.com/xianhua/2018_9/13/16/50/14_226.jpg" class="return_index_img" @tap="toIndex"></cover-image>
            </cover-view>
            <cover-view class="location">
              <cover-image src="https://image1.sansancloud.com/xianhua/2018_9/13/16/50/14_232.jpg" class="location_img" @tap="clickcontrol"></cover-image>
            </cover-view>
          </cover-view>
          <cover-view class="product_data" v-if="productDetail!=null">
            <cover-view class="product_info">
              <cover-image class="product_info_left" :src="(productDetail.productInfo.imagePath+'?x-oss-process=style/preview_120')"></cover-image>
              <cover-view class="product_info_center">
                <cover-view class="product_info_name">{{productDetail.productInfo.name}}</cover-view>
                <cover-view class="product_info_service_time">
                  <cover-image class="product_info_service_time_img" src="https://image1.sansancloud.com/santigongxiang/2018_10/10/18/22/0_933.jpg"></cover-image>
                  <cover-view class="product_info_service_time_value">{{productDetail.productInfo.categoryName}}</cover-view>
                </cover-view>
                <cover-view class="product_info_service_addr">
                  <cover-image class="product_info_service_addr_img" src="https://image1.sansancloud.com/xianhua/2018_9/13/17/57/21_219.jpg"></cover-image>
                  <cover-view class="product_info_service_addr_value" style="width:96%; word-break: break-all;text-overflow: ellipsis;white-space: nowrap;">{{productDetail.productInfo.location}}</cover-view>
                </cover-view>
              </cover-view>
              <cover-view class="product_info_right" @tap="toProductDetail" :data-info="productDetail.productInfo">
                <cover-view class="line"></cover-view>
                <cover-image src="https://image1.sansancloud.com/xianhua/2018_9/13/20/11/36_801.jpg?x-oss-process=style/preview_120" class="navigation"></cover-image>
              </cover-view>
            </cover-view>
          </cover-view>
      </scroll-view>
    </block>
  

</view>
</template>

<script>

export default {
  data() {
    return {
      setting: null,
      // setting   
      productData: [],
      // 商品数据 
      productType: [],
      sysWidth: 320,
      //图片大小
      positionTab: '',
      ProductshowWay: 1,
      // ProductshowWay列表显示方法 (默认显示地图)
      localPoint: {
        longitude: '0',
        latitude: '0'
      },
      productDetail: null,
      markers: [{
        iconPath: "/wxcomponents/images/icons/mapItem.png",
        id: 0,
        width: 20,
        heigth: 20,
        latitude: 26.060701172100124,
        longitude: 119.30130341796878
      }],

      /* 全部参数 */
      params: {
        categoryId: "",
        platformNo: "",
        belongShop: "",
        page: 1,
        productName: "",
        orderType: "",
        saleTypeId: "",
        promotionId: "",
        shopProductType: "",
        latitude: '0',
        longitude: '0',
        useLocation: 1
      },
      listPage: {
        page: 1,
        pageSize: 0,
        totalSize: 0,
        curpage: 1
      },
      currentItem: "",
      showType: false,
      bindProductTypeIndex: "",
      focusTypeItem: ""
    };
  },

  components: {},
  props: {},

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let that = this;
    that.initSetting();
    wx.getLocation({
      type: 'gcj02',
      //返回可以用于wx.openLocation的经纬度
      success: function (res) {
        console.log(res);
        that.localPoint.latitude = res.latitude;
        that.localPoint.longitude = res.longitude;
        that.params.latitude = res.latitude;
        that.params.longitude = res.longitude;
        console.log("options", options); // that.setData({ positionTab: options.productTypeId})
        // options.categoryId = options.productTypeId;//当前类目Id
        // let parentCategoryId = options.parentCategoryId||0;//父级类目Id
        // that.getProductType(parentCategoryId, options.categoryId, that.bindTypeItem)
        // that.bindTypeItem(options.productTypeId)

        if (options.productTypeId) {
          that.setData({
            positionTab: options.productTypeId
          });
          options.categoryId = options.productTypeId;
          that.getProductType(options.categoryId, that.bindTypeItem);
        } else {
          that.getProductType(options.categoryId);
        } // if (options.productTypeId) {
        //   that.setData({ positionTab: options.productTypeId })
        //   options.categoryId = options.productTypeId
        //   that.bindTypeItem(options.productTypeId)
        // }


        if (!!options.forceSearch && options.forceSearch == 2) {
          that.setData({
            ProductshowWay: 2
          });
        } else {
          that.setData({
            ProductshowWay: 1
          });
        }

        for (let i in options) {
          for (let j in that.params) {
            if (i.toLowerCase() == j.toLowerCase()) {
              that.params[j] = options[i];
            }
          }
        }

        that.setData({
          params: that.params,
          localPoint: that.localPoint
        });
        console.log(that.params);
        that.getData(that.params, 2);
      }
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {},

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {},

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    this.listPage.page = 1;
    this.params.page = 1;
    this.getData(this.params, 2);
    wx.showNavigationBarLoading();
    wx.hideNavigationBarLoading(); //完成停止加载

    wx.stopPullDownRefresh(); //停止下拉刷新
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    var that = this;

    if (that.listPage.totalSize > that.listPage.curPage * that.listPage.pageSize) {
      that.listPage.page++;
      that.params.page++;
      this.getData(this.params);
    }
  },
  methods: {
    getProductType: function (categoryId) {
      var customIndex = getApp().globalData.AddClientUrl("/wx_get_categories_only_by_parent.html", {
        categoryId: categoryId || 0
      }); // wx.showLoading({
      //   title: 'loading'
      // })

      getApp().globalData.showToastLoading('loading', true);
      var that = this;
      wx.request({
        url: customIndex.url,
        header: getApp().globalData.header,
        success: function (res) {
          wx.hideLoading();
          console.log("getProductType", res.data);

          if (res.data.errcode == 0) {
            that.setData({
              productType: res.data.relateObj
            });
          } else {
            that.setData({
              productType: that.productType
            });
          }

          that.productType.unshift({
            id: categoryId || 0,
            name: "全部"
          });

          for (let i = 0; i < that.productType.length; i++) {
            that.productType[i].colorAtive = '#888';
          }

          that.productType[0].colorAtive = that.setting.platformSetting.defaultColor;
          that.productType[0].active = true;
          that.setData({
            productType: that.productType
          });
          console.log("that.data.productType", that.productType);
          wx.hideLoading();
        },
        fail: function (res) {
          console.log("fail");
          wx.hideLoading();
          getApp().globalData.loadFail();
        }
      });
    },

    toIndex() {
      getApp().globalData.toIndex();
    },

    clickcontrol(e) {
      //回到定位的
      let mpCtx = wx.createMapContext("map");
      mpCtx.moveToLocation();
    },

    getCenterPoint(callback) {
      let that = this;
      var mapCtx = wx.createMapContext('map');
      mapCtx.getCenterLocation({
        success: function (res) {
          console.log('res', res);
          that.params.latitude = res.latitude;
          that.params.longitude = res.longitude;
          that.setData({
            params: that.params
          });

          if (callback) {
            callback(that.params, 2);
          }
        }
      }); //获取当前地图的中心经纬度
    },

    regionchange(e) {
      console.log('===regionchange===', e);

      if (e.type == 'end') {
        if (e.causedBy == 'scale') {
          console.log('====scale====');
        } else if (e.causedBy == 'drag') {
          console.log('====drag====');
          this.getCenterPoint(this.getData);
        } else {
          console.log('====all====');
          this.getCenterPoint(this.getData);
        }
      }
    },

    markertap(e) {
      console.log(e.markerId);
      this.toProductDetailMap(e.markerId);
    },

    controltap(e) {
      console.log(e);
    },

    hiddenProInfo(e) {
      console.log(e);
      this.setData({
        productDetail: null
      });
    },

    /* 点击分类大项 */
    bindTypeItem: function (event) {
      console.log(event.currentTarget.dataset.type);
      let that = this;

      for (let i = 0; i < that.productType.length; i++) {
        if (that.productType[i].id == event.currentTarget.dataset.type.id) {
          that.productType[i].active = true;
          that.productType[i].colorAtive = that.setting.platformSetting.defaultColor;
          that.setData({
            currentItem: that.productType[i]
          });
        } else {
          that.productType[i].active = false;
          that.productType[i].colorAtive = '#888';
        }
      }

      that.setData({
        productType: that.productType
      });
      that.listPage.page = 1;
      that.params.page = 1;

      if (event.currentTarget.dataset.type.id == "all") {
        that.params.categoryId = '';
        that.getData(this.params, 2);
        that.setData({
          showType: false,
          bindProductTypeIndex: null
        });
        var allItem = {
          id: ""
        };
        that.setData({
          focusTypeItem: allItem
        });
      } else {
        that.setData({
          focusTypeItem: event.currentTarget.dataset.type
        });
        var focus = event.currentTarget.dataset.type; //if (focus.children.length == 0) {

        that.params.categoryId = focus.id;
        that.setData({
          productDetail: null
        });
        that.getData(this.params, 2);
        that.setData({
          showType: false,
          bindProductTypeIndex: null
        }); //}
      }
    },

    /* 点击分类大项 */
    // bindTypeItem: function (event) {
    //   let onId;
    //   if (event && event.currentTarget){
    //     onId = event.currentTarget.dataset.type.id
    //     console.log('====bindTypeItem currentTarget====',onId)
    //   } else if (event && !event.currentTarget){
    //     onId = event
    //     console.log('====bindTypeItem event====',onId)
    //   }
    //   console.log(event)
    //   console.log("this.data.setting.platformSetting",this.data.setting)
    //   for (let i = 0; i < this.data.setting.platformSetting.categories.length; i++) {
    //     if (this.data.setting.platformSetting.categories[i].id == onId ) {
    //       this.data.setting.platformSetting.categories[i].active = true
    //       console.log(this.data.setting.platformSetting.defaultColor)
    //       this.data.setting.platformSetting.categories[i].colorAtive =this.data.setting.platformSetting.defaultColor;
    //     }
    //     else {
    //       this.data.setting.platformSetting.categories[i].active = false
    //       this.data.setting.platformSetting.categories[i].colorAtive = '#888';
    //     }
    //   }
    //   this.setData({
    //     setting: this.data.setting,
    //   })
    //   this.listPage.page = 1
    //   this.params.page = 1
    //   if (onId == "all") {
    //     this.params.categoryId = ''
    //     this.getData(this.params, 2)
    //   } else {
    //     this.params.categoryId = onId
    //     this.getData(this.params, 2)
    //   }
    // },

    /* 获取数据 */
    getData: function (param, ifAdd) {
      //根据把param变成&a=1&b=2的模式
      if (!ifAdd) {
        ifAdd = 1;
      }

      var customIndex = getApp().globalData.AddClientUrl("/more_product_list.html", param); // wx.showLoading({
      //   title: 'loading'
      // })

      getApp().globalData.showToastLoading('loading', true);
      var that = this;
      wx.request({
        url: customIndex.url,
        header: getApp().globalData.header,
        success: function (res) {
          wx.hideLoading();
          console.log(res.data);
          that.listPage.pageSize = res.data.pageSize;
          that.listPage.curPage = res.data.curPage;
          that.listPage.totalSize = res.data.totalSize;
          let dataArr = that.productData;
          let tagArray = [];

          if (ifAdd == 2) {
            dataArr = [];
          }

          if (!res.data.result || res.data.result.length == 0) {
            that.setData({
              productData: null
            });
          } else {
            if (dataArr == null) {
              dataArr = [];
            }

            dataArr = dataArr.concat(res.data.result);

            for (let i = 0; i < dataArr.length; i++) {
              if (dataArr[i].tags && dataArr[i].tags != '') {
                tagArray = dataArr[i].tags.slice(1, -1).split("][");
                dataArr[i].tagArray = tagArray;
              }
            }

            that.setData({
              productData: dataArr
            });
          }

          that.setData({
            markers: that.productData
          });
          let conut = 0;

          if (that.markers) {
            for (let i = 0; i < that.markers.length; i++) {
              if (that.markers[i].categoryIcon) {
                that.downProIcon(that.markers[i].categoryIcon, function (url) {
                  conut++;
                  that.markers[i].iconPath = url;
                  that.markers[i].width = 32;
                  that.markers[i].height = 32;

                  if (conut == that.markers.length) {
                    that.setData({
                      markers: that.markers
                    });
                    console.log('==that.data.markersHave===', that.markers);
                  }
                });
              } else {
                conut++;
                that.markers[i].iconPath = '/wxcomponents/images/icons/mapItem.png';
                that.markers[i].width = 32;
                that.markers[i].height = 32;

                if (conut == that.markers.length) {
                  that.setData({
                    markers: that.markers
                  });
                  console.log('==that.data.markers===', that.markers);
                }
              }
            }
          }

          wx.hideLoading();
        },
        fail: function (res) {
          console.log("fail");
          wx.hideLoading();
          getApp().globalData.loadFail();
        }
      });
    },
    downProIcon: function (url, callback) {
      var _this = this;

      if (getApp().globalData.mapProIconArray[encodeURIComponent(url)]) {
        console.log('已存在', encodeURIComponent(url));
        callback(getApp().globalData.mapProIconArray[encodeURIComponent(url)]);
        return;
      }

      wx.downloadFile({
        url: url.replace('http', 'https'),
        success: function (res) {
          console.log('下载图片', res);

          if (res.statusCode == 200) {
            callback(res.tempFilePath);
            getApp().globalData.mapProIconArray[encodeURIComponent(url)] = res.tempFilePath;
          }
        }
      });
    },

    /* 查找商品 */
    getSearchProductName: function (e) {
      console.log(e);

      if (e.detail.value) {
        this.params.productName = e.detail.value;
      } else {
        this.params.productName = '';
      }

      var that = this;
      var customIndex = this.more_product_list_URLFun(this.params);
      console.log(customIndex); // wx.showLoading({
      //   title: 'loading'
      // })

      getApp().globalData.showToastLoading('loading', true);
      wx.request({
        url: customIndex.url,
        header: getApp().globalData.header,
        success: function (res) {
          console.log(res.data);
          wx.hideLoading();

          if (!res.data.result || res.data.result.length == 0) {
            that.setData({
              productData: null
            });
          } else {
            let tagArray;

            for (let i = 0; i < res.data.result.length; i++) {
              if (res.data.result[i].tags && res.data.result[i].tags != '') {
                tagArray = res.data.result[i].tags.slice(1, -1).split("][");
                res.data.result[i].tagArray = tagArray;
              }
            }

            that.setData({
              productData: res.data.result
            });
          }

          that.setData({
            markers: that.productData
          });
          let conut = 0;

          if (that.markers) {
            for (let i = 0; i < that.markers.length; i++) {
              if (that.markers[i].categoryIcon) {
                that.downProIcon(that.markers[i].categoryIcon, function (url) {
                  conut++;
                  that.markers[i].iconPath = url;
                  that.markers[i].width = 32;
                  that.markers[i].height = 32;

                  if (conut == that.markers.length) {
                    that.setData({
                      markers: that.markers
                    });
                    console.log('==that.data.markersHave===', that.markers);
                  }
                });
              } else {
                conut++;
                that.markers[i].iconPath = '/wxcomponents/images/icons/mapItem.png';
                that.markers[i].width = 32;
                that.markers[i].height = 32;

                if (conut == that.markers.length) {
                  that.setData({
                    markers: that.markers
                  });
                  console.log('==that.data.markers===', that.markers);
                }
              }
            }
          }
        },
        fail: function () {
          wx.hideLoading();
          getApp().globalData.loadFail();
        }
      });
    },
    more_product_list_URLFun: function (params) {
      let resule = getApp().globalData.AddClientUrl("/more_product_list.html", params);
      return resule;
    },

    /* 商品显示方法 */
    bindProductshowWay: function () {
      if (this.ProductshowWay == 1) {
        this.setData({
          ProductshowWay: 2
        });
      } else {
        this.setData({
          ProductshowWay: 1
        });
      }
    },
    toProductDetail: function (event) {
      console.log("--------toProductDetail------", event);
      console.log(event.currentTarget.dataset.info);
      var info = event.currentTarget.dataset.info;
      let id;
      let belongShopId = info.belongShopId;

      if (info.productId) {
        id = info.productId;
      } else {
        id = info.id;
      }

      let url = 'product_detail.html?id=' + id;
      getApp().globalData.linkEvent(url);
    },
    toProductDetailMap: function (id) {
      console.log("--------toProductDetailMap------");
      console.log(id);
      var param = {
        productId: id
      };
      let customIndex = getApp().globalData.AddClientUrl("/product_detail.html", param);
      var that = this;
      that.setData({
        productDetail: null
      });
      wx.request({
        url: customIndex.url,
        header: getApp().globalData.header,
        success: function (res) {
          console.log(res.data);
          that.setData({
            productDetail: res.data
          });
        },
        fail: function (res) {
          console.log("fail");
          getApp().globalData.loadFail();
        },
        complete: function () {}
      });
    },

    initSetting() {
      this.setData({
        setting: getApp().globalData.setting
      });

      for (let i = 0; i < this.setting.platformSetting.categories.length; i++) {
        this.setting.platformSetting.categories[i].colorAtive = '#888';
      }

      this.setting.platformSetting.categories[0].colorAtive = this.setting.platformSetting.defaultColor;
      this.setData({
        setting: this.setting
      });
    },

    setData: function (obj) {
      let that = this;
      let keys = [];
      let val, data;
      Object.keys(obj).forEach(function (key) {
        keys = key.split('.');
        val = obj[key];
        data = that.$data;
        keys.forEach(function (key2, index) {
          if (index + 1 == keys.length) {
            that.$set(data, key2, val);
          } else {
            if (!data[key2]) {
              that.$set(data, key2, {});
            }
          }

          data = data[key2];
        });
      });
    }
  }
};
</script>
<style>
@import "./index.css";
</style>